package Servlets;

import DAOS.ErpMobileDAO;
import DTOS.ArticuloDTO;
import EstructuraPrincipal.PrincipalTerminal;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Alan Gonzalez
 */
@WebServlet(name = "Controlador", urlPatterns = {"/Controlador"})
public class Controlador extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            String action = request.getParameter("action");
            HttpSession session = request.getSession();

            if (action.equals("menuPrincipal")) {
                this.menuPrincipal(request, response, session);

                // CONTROLADORES PARA EL TOTAL DE EXISTENCIAS
            } else if (action.equals("totalExistencias")) {                     // SERVICIO OK
                this.totalExistencias(request, response, session);
            } else if (action.equals("totalExistenciasSearch")) {               // SERVICIO OK  
                this.totalExistenciasSearch(request, response, session);

                // CONTROLADORES PARA EL PERFIL COMPLETO DEL ARTICULO
            } else if (action.equals("perfilArticuloCB")) {                     // 
                this.perfilArticuloCB(request, response, session);
            } else if (action.equals("perfilArticuloCBRequest")) {              // 
                this.perfilArticuloCBRequest(request, response, session);

                //CONTROLADORES PARA LAS ENTRADAS UNITARIAS 
            } else if (action.equals("entradaUnitariaCB")) {              // 
                this.entradaUnitariaCB(request, response, session);
            } else if (action.equals("entradaUnitariaCBRequest")) {              // 
                this.entradaUnitariaCBRequest(request, response, session);

//CONTROLADORES PARA LAS SALIDAS UNITARIAS 
            } else if (action.equals("salidaUnitariaCB")) {              // 
                this.salidaUnitariaCB(request, response, session);
            } else if (action.equals("salidaUnitariaCBRequest")) {              // 
                this.salidaUnitariaCBRequest(request, response, session);

//CONTROLADORES PARA EL LISTADO DE ACTIVIDADES DEL SISTEMA < < LOGS > >
            } else if (action.equals("registros")) {              // 
                this.registrosActividad(request, response, session);                
                
// CONTROLADOR PARA EL REGISTRO DE NUEVOS PRODUCTOS DESDE EL TERMINAL
            } else if (action.equals("nuevoProductoCB")) {              // 
                this.nuevoProductoCB(request, response, session);

            } else {
                System.out.println("ERROR AL ENTRAR A UN SERVICIO DENTRO DE CONTROLADOR ERP MOBILE, EL SERVICIO :"
                        + action + " NO EXISTE");
            }

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * ALAN GONZALEZ SERVICIO PARA MOSTRAR MENU PRINCIPAL
     *
     * @param request
     * @param response
     * @param session
     */
    public void menuPrincipal(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        RequestDispatcher d = request.getRequestDispatcher("Interfaces/MenuPrincipal.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO PRINCIPAL DE COMPRAS CARGA TODAS LAS ORDENES DE
     * COMPRA
     *
     * @param request
     * @param response
     * @param session
     */
    public void totalExistencias(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        PrincipalTerminal principal;

        if (session.getAttribute("principalColectorExistencias") != null) {
            principal = (PrincipalTerminal) session.getAttribute("principalColectorExistencias");
        } else {
            principal = new PrincipalTerminal();
        }

        session.setAttribute("principalColectorExistencias", principal);
        RequestDispatcher d = request.getRequestDispatcher("Interfaces/existencias/cbExistencia.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ ESTE SERVICIO RECUPERA EL CB PARA ONTENER LAS EXISTENCIAS
     * DE ESE ITEM
     *
     * @param request
     * @param response
     * @param session
     */
    public void totalExistenciasSearch(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        ArticuloDTO articuloDTO = new ArticuloDTO();
        ErpMobileDAO datosTerminal = new ErpMobileDAO();
        PrincipalTerminal principal = new PrincipalTerminal();

        String cb = request.getParameter("cb");
        articuloDTO = datosTerminal.articuloDescripcion(cb);

        principal.setBanderaMensajeExistenciaCB(1);

        if (articuloDTO != null) {                      // verifico que el articulo este registrado en la base de datos
            principal.setValorMensajeExistenciasaCB(1); // mensaje correcto
        } else {
            principal.setValorMensajeExistenciasaCB(0); // mensaje correcto
        }

        principal.setArticulo(articuloDTO);
        session.setAttribute("principalColectorExistencias", principal);
        RequestDispatcher d = request.getRequestDispatcher("Interfaces/existencias/cbExistencia.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO DE INTERFAZ DEL CB PARA PERFILES DE ARTICULOS
     *
     * @param request
     * @param response
     * @param session
     */
    public void perfilArticuloCB(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        RequestDispatcher d = request.getRequestDispatcher("Interfaces/perfiles/cbPerfiles.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ EL SERVICIO RECUPERA EL CB Y DEVUELVE EL PERFIL DEL
     * ARTICULO
     *
     * @param request
     * @param response
     * @param session
     */
    public void perfilArticuloCBRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String cb = request.getParameter("cb");
        ErpMobileDAO terminalDatos = new ErpMobileDAO();
        PrincipalTerminal principal = new PrincipalTerminal();
        ArticuloDTO articulo = new ArticuloDTO();
        articulo = terminalDatos.articuloDescripcion(cb);
        if (articulo != null) {
            // REDIRECCIONO AL PERFIL
            principal.setArticulo(articulo);
            session.setAttribute("principalColector", principal);
            RequestDispatcher d = request.getRequestDispatcher("Interfaces/perfiles/perfil.jsp");
            try {
                d.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            RequestDispatcher onError = request.getRequestDispatcher("Interfaces/perfiles/error.jsp");
            try {
                onError.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO QUE MUESTRA LA INTERFAZ DE CB PARA EL INGRESO
     * UNITARIO
     *
     * @param request
     * @param response
     * @param session
     */
    public void entradaUnitariaCB(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        RequestDispatcher showForm = request.getRequestDispatcher("Interfaces/entradas/cbEntradas.jsp");
        try {
            showForm.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO QUE RECUPERA EL CB Y GENERA LA ENTRADA
     *
     * @param request
     * @param response
     * @param session
     */
    public void entradaUnitariaCBRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String cb = request.getParameter("cb");
        PrincipalTerminal principal = new PrincipalTerminal();
        ArticuloDTO articulo = new ArticuloDTO();
        ErpMobileDAO terminalDatos = new ErpMobileDAO();
        articulo = terminalDatos.articuloDescripcion(cb);
// VERIFICANDO LA EXISTENCIA DEL PERFIL DEL PRODUCTO
        if (articulo != null) {
// SE REALIZA EL INGRESO
            terminalDatos.ingresaExistenciaUnitaria(cb);
// SE REALIZA EL REGISTRO DE LA ACTIVIDAD (LOG DEL SISTEMA)
            RequestDispatcher Redireccion = request.getRequestDispatcher("./Controlador?action=entradaUnitariaCB");
            try {
                Redireccion.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            System.out.println("ERROR NO EXISTE EL PERFIL");
            RequestDispatcher onError = request.getRequestDispatcher("Interfaces/entradas/error.jsp");
            try {
                onError.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * ALAN GONZALEZ SALIDA UNITARIA
     *
     * @param request
     * @param response
     * @param session
     */
    public void salidaUnitariaCB(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        RequestDispatcher cb = request.getRequestDispatcher("Interfaces/salidas/cbSalidas.jsp");
        try {
            cb.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO QUE RECUPERA EL CB Y GENERA LA SALIDA Y SU LOG
     *
     * @param request
     * @param response
     * @param session
     */
    public void salidaUnitariaCBRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String cb = request.getParameter("cb");
        PrincipalTerminal principal = new PrincipalTerminal();
        ArticuloDTO articulo = new ArticuloDTO();
        ErpMobileDAO terminalDatos = new ErpMobileDAO();
        articulo = terminalDatos.articuloDescripcion(cb);

        if (articulo != null) {
            terminalDatos.salidaExistenciaUnitaria(cb);
            RequestDispatcher Redireccion = request.getRequestDispatcher("./Controlador?action=salidaUnitariaCB");
            try {
                Redireccion.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            RequestDispatcher onError = request.getRequestDispatcher("Interfaces/salidas/error.jsp");
            try {
                onError.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * ALAN GONZALEZ
     *
     * @param request
     * @param response
     * @param session
     */
    public void registrosActividad(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        int numeroRegistrosSolicitados = Integer.parseInt(request.getParameter("limiteLogs"));

        PrincipalTerminal principal = new PrincipalTerminal();
        ErpMobileDAO terminalDatos = new ErpMobileDAO();

        Vector logs = new Vector();

        switch (numeroRegistrosSolicitados) {
            case 15:
                logs = terminalDatos.eventos(15);
                break;
            case 30:
                logs = terminalDatos.eventos(30);
                break;
            case 0:
                logs = terminalDatos.todoEventos();
                break;
        }

        principal.setEventos(logs);
        session.setAttribute("principalTerminalLogs", principal);
        RequestDispatcher abc = request.getRequestDispatcher("Interfaces/logs/logMain.jsp");
        try {
            abc.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ
     *
     * @param request
     * @param response
     * @param session
     */
    public void nuevoProductoCB(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        int index = Integer.parseInt(request.getParameter("index"));

        switch (index) {
            case 1: // MOSTRAR CB INTERFAZ
                RequestDispatcher abc = request.getRequestDispatcher("Interfaces/registro/cbRegistro.jsp");
                try {
                    abc.forward(request, response);
                } catch (ServletException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case 2: // MOSTRAR CB INTERFAZ
                String cb = request.getParameter("cb");
                session.setAttribute("cbNuevoRegistro", cb);
                
                RequestDispatcher onError = request.getRequestDispatcher("Interfaces/salidas/error.jsp");
                try {
                    onError.forward(request, response);
                } catch (ServletException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                }

                break;

        }

    }
}
